package com.github.shiqiyue.learn.curator.recipe;

import com.github.shiqiyue.learn.curator.ClientUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/***
 * 选举-测试
 * @author wenyao.wu
 * @date 2019/1/21
 */
public class ElectTest {

    private static final Logger logger = LoggerFactory.getLogger(ElectTest.class);

    public static void main(String[] args) throws IOException {
        CuratorFramework client = ClientUtil.getClient(null);
        String path = "/elect1";
        LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
                // this callback will get called when you are the leader
                // do whatever leader work you need to and only exit
                // this method when you want to relinquish leadership
                logger.info("获得领导权");
                Thread.sleep(10000);
                logger.info("执行结束，放弃领导权");
            }
        };

        LeaderSelector selector = new LeaderSelector(client, path, listener);
        // not required, but this is behavior that you will probably expect
        selector.autoRequeue();
        selector.start();
        System.in.read();
        client.close();
    }
}
